package com.xin.marcus.service.impl;

import com.alibaba.excel.EasyExcel;
import com.xin.marcus.entity.HlyPersonalReimbursement;
import com.xin.marcus.entity.TestUser;
import com.xin.marcus.mapper.TestUserMapper;
import com.xin.marcus.service.DownLoadExcelService;
import com.xin.marcus.utils.ExcelReadListener;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


@Service
public class DownLoadExcelServiceImpl implements DownLoadExcelService {
    @Resource
    private TestUserMapper testUserMapper;

    /**
     * 文件下载
     * @author xin.wang
     * @date 2023/10/26  9:56
     */
    @Override
    public void downLoadExcel(HttpServletRequest request,
                              HttpServletResponse response) throws IOException {
        //设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //设置防止中文乱码
        String fileName = URLEncoder.encode("用户信息","utf-8");
        //文件下载方式
        response.setHeader("Content-disposition","attachment;filename" + fileName + ".xlsx");
        //获取表数据
        List<HlyPersonalReimbursement> testUsers = testUserMapper.hlyPersonalReimbursementList();
        //构建写入到excel文件的数据
        EasyExcel.write(response.getOutputStream(),HlyPersonalReimbursement.class)
                .sheet("用户信息.xlsx")
                .doWrite(testUsers);
    }

    /**
     * 文件上传
     * @author xin.wang
     * @date 2023/10/26  9:56
     */
    @Override
    public String uploadExcel(@RequestParam("file") Part part) throws IOException {
       //获取上传的文件流
        InputStream inputStream = part.getInputStream();
        //读取Excel
        EasyExcel.read(inputStream,TestUser.class,new ExcelReadListener(testUserMapper))
                .sheet()
                .doRead();

        return "上传成功!!!";
    }
}
